package com.lishe.lishe.lishe.module.myorder.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.AddressBean;
import com.lishe.lishe.lishe.bean.AddressItem;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.me.activity.AddressManageActivity;
import com.lishe.lishe.lishe.module.myorder.bean.ConfirmOrderBean;
import com.lishe.lishe.lishe.module.myorder.view.OrderInfoDialog;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.module.shopingcart.bean.CartListBean;
import com.lishe.lishe.lishe.module.shopingcart.bean.ShopListBean;
import com.lishe.lishe.lishe.module.shopingcart.bean.SubmitOrderBean;
import com.lishe.lishe.lishe.utils.FormatUtil;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.lishe.lishe.net.BaseHttpLoader;
import com.lishe.lishe.net.BaseProtocal;
import com.lishe.lishe.net.NetAPI;
import com.lishe.lishe.net.ResultListener;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import okhttp3.ResponseBody;

/**
 * Bin
 * 确认订单
 */

public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener {

    private TextView mTvName;
    private TextView mTvPhone;
    private TextView mTvAddress;
    private TextView mTvCount;
    private TextView mTvIntegral;
    private LinearLayout mContentLayout;
    private SubmitOrderBean.DataBean mDataBean;
    private TextView mCouponText;
    private String mCouponDecrease = "0";
    private View mCouponLayout;
    private String mCartTotalPrice; //总价格
    private String mTotalCartDelivery;  //总运费
    private ArrayList<String> mDefaultPostfees = new ArrayList<>();  //默认邮费数组

    public static void jump(Activity activity, SubmitOrderBean.DataBean data) {
        Intent intent = new Intent(activity, ConfirmOrderActivity.class);
        intent.putExtra("data", data);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDataBean = (SubmitOrderBean.DataBean) getIntent().getSerializableExtra("data");
        mCartTotalPrice = mDataBean.cartTotalPrice;
        mTotalCartDelivery = mDataBean.totalCartDelivery;
        for (int i = 0; i < mDataBean.shopList.size(); i++) {
            mDefaultPostfees.add(mDataBean.shopList.get(i).postFree);
        }
        regisBrocastReciver();
        setContentView(R.layout.activity_confirm_order);
        initView();
        initListener();
        initData(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
    }

    private void initView() {
        TextView title = findViewById(R.id.title_text_title);
        title.setText(getString(R.string.confirm_order));
        //地址栏
        mTvName = findViewById(R.id.receive_name);
        mTvPhone = findViewById(R.id.receive_phone);
        mTvAddress = findViewById(R.id.receive_address);
        //底部价格信息
        mTvCount = findViewById(R.id.totalcount);
        mTvIntegral = findViewById(R.id.total_integral);
        mContentLayout = findViewById(R.id.content_layout);
    }

    private void initListener() {
        findViewById(R.id.submit).setOnClickListener(this);
        findViewById(R.id.info_layout).setOnClickListener(this);
        findViewById(R.id.address_layout).setOnClickListener(this);
        findViewById(R.id.title_left_button).setOnClickListener(this);
    }

    /**
     * 数据初始化
     */
    private void initData(boolean isResetCoupon) {
        if (mDataBean.defAddrInfo != null) {
            mTvName.setText("收货人: " + mDataBean.defAddrInfo.name);
            mTvPhone.setText(mDataBean.defAddrInfo.mobile);
            mTvAddress.setText("收货地址: " + mDataBean.defAddrInfo.area + mDataBean.defAddrInfo.addr);
        }

        mTvIntegral.setText(FormatUtil.numFormat(Double.parseDouble(mDataBean.cartTotalPrice) * 100) + "积分");
        //统计共几件商品
        mContentLayout.removeAllViews();
        for (ShopListBean bean : mDataBean.shopList) {
            View businessLayout = getLayoutInflater().inflate(R.layout.item_business_layout, null);
            TextView tvFreight = businessLayout.findViewById(R.id.freight);
            TextView tvStoreName = businessLayout.findViewById(R.id.store_name);
            TextView tvGoodsCount = businessLayout.findViewById(R.id.goods_count);
            TextView tvGoodsMoney = businessLayout.findViewById(R.id.goods_money);
            if (bean.postFree == null || Double.parseDouble(bean.postFree) == 0) {
                tvFreight.setText(getString(R.string.free));
            } else {
                tvFreight.setText("¥" + bean.postFree);
            }
            tvStoreName.setText(bean.shop_name);
            tvGoodsMoney.setText("¥" + FormatUtil.numFormat(Double.parseDouble(bean.totalPrice) + Double.parseDouble(bean.postFree)));
            tvGoodsCount.setText("共" + getGoodsCountByShopId(bean.shop_id) + "件");
            //商品
            LinearLayout goods_layout = businessLayout.findViewById(R.id.goods_layout);
            goods_layout.removeAllViews();
            for (final CartListBean cartBean : mDataBean.cartList) {
                if (!cartBean.shop_id.equals(bean.shop_id)) {
                    continue;
                }
                View goodsLayout = getLayoutInflater().inflate(R.layout.item_goodsinfo, null);
                ImageView goodsImg = goodsLayout.findViewById(R.id.goods_img);
                TextView goods_name = goodsLayout.findViewById(R.id.goods_name);
                TextView goods_spec = goodsLayout.findViewById(R.id.goods_spec);
                TextView goodsPrice = goodsLayout.findViewById(R.id.goods_price);
                TextView goodsCount = goodsLayout.findViewById(R.id.goods_count);
                goodsCount.setText("x" + cartBean.quantity);
                goods_name.setText(cartBean.title);
                goods_spec.setText(cartBean.spec_info);
                goodsPrice.setText("¥" + cartBean.price);
                ImageLoaderUtils.displayImage(this, cartBean.image_default_id, goodsImg, R.drawable.defalut_img);
                /*goodsLayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        MallGoodsActivity.jump(ConfirmOrderActivity0.this, cartBean.item_id);
                    }
                });*/
                goods_layout.addView(goodsLayout);
            }
            mContentLayout.addView(businessLayout);
        }
        /**
         * 优惠券
         */
        if (isResetCoupon) {
            mCouponLayout = getLayoutInflater().inflate(R.layout.item_couponlayout, null);
            mCouponText = mCouponLayout.findViewById(R.id.couponText);
            mCouponLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(ConfirmOrderActivity.this, SelectCouponActivity.class);
                    i.putExtra("CouponList", (Serializable) mDataBean.coupons);
                    startActivityForResult(i, 0);
                }
            });
            if (mDataBean.coupons.size() == 0) {
                mCouponText.setText("暂无可用");
                mCouponText.setTextColor(this.getResources().getColor(R.color.gray_9));
            } else {
                mCouponText.setText(mDataBean.coupons.size() + "张可用");
                mCouponText.setTextColor(this.getResources().getColor(R.color.gray_9));
            }
        }
        mContentLayout.addView(mCouponLayout);
        mTvCount.setText("共" + getTotalCount() + "件");
    }

    private int getTotalCount() {
        int count = 0;
        for (int i = 0; i < mDataBean.cartList.size(); i++) {
            count += Integer.parseInt(mDataBean.cartList.get(i).quantity);
        }
        return count;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1:
                for (int i = 0; i < mDataBean.coupons.size(); i++) {
                    mDataBean.coupons.get(i).isSelect = false;
                }
                mCouponDecrease = "0";
                mDataBean.cartTotalPrice = mCartTotalPrice;
                mDataBean.totalCartDelivery = mTotalCartDelivery;
                mTvIntegral.setText(FormatUtil.numFormat(Double.parseDouble(mDataBean.cartTotalPrice) * 100) + "积分");
                for (int i = 0; i < mDefaultPostfees.size(); i++) {
                    mDataBean.shopList.get(i).postFree = mDefaultPostfees.get(i);
                }
                initData(true);
                break;
            case 2:
                int position = data.getIntExtra("position", 0);
                for (int i = 0; i < mDataBean.coupons.size(); i++) {
                    mDataBean.coupons.get(i).isSelect = false;
                }
                mDataBean.coupons.get(position).isSelect = true;
                mCouponDecrease = mDataBean.coupons.get(position).couponDecrease;
                mCouponText.setText("-¥" + mDataBean.coupons.get(position).couponDecrease);
                mCouponText.setTextColor(this.getResources().getColor(R.color.gray_3));
                String[] postfees = mDataBean.coupons.get(position).postfees.split(",");
                for (int i = 0; i < mDataBean.shopList.size(); i++) {
                    mDataBean.shopList.get(i).postFree = postfees[i];
                }
                mDataBean.cartTotalPrice = mDataBean.coupons.get(position).totalPrice;
                mDataBean.totalCartQuantity = mDataBean.coupons.get(position).actualPostfee;
                initData(false);
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.submit:
                submitOrder();
                break;
            case R.id.address_layout:
                AddressManageActivity.jump(ConfirmOrderActivity.this);
                break;
            case R.id.info_layout:
                new OrderInfoDialog(context,
                        mDataBean.cartTotalPrice,
                        FormatUtil.numFormat(Double.parseDouble(mDataBean.cartTotalPrice) - Double.parseDouble(mDataBean.totalCartDelivery)),
                        mDataBean.totalCartDelivery,
                        mCouponDecrease,
                        mDataBean.coupons.size(),
                        getIsUseCoupon()).show();
                break;
        }
    }

    /**
     * 通过shop_id判断该店铺有多少个商品
     */
    private int getGoodsCountByShopId(String shop_id) {
        int count = 0;
        for (int i = 0; i < mDataBean.cartList.size(); i++) {
            if (shop_id.equals(mDataBean.cartList.get(i).shop_id)) {
                count += 1;
            }
        }
        return count;
    }

    private boolean getIsUseCoupon() {
        for (int i = 0; i < mDataBean.coupons.size(); i++) {
            if (mDataBean.coupons.get(i).isSelect) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取默认收货地址
     */
    private void getReceiveAddress() {
        BaseHttpLoader loader = new BaseHttpLoader(AddressBean.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.getAddress(Globals.getToken());
            }
        };
        loader.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                AddressBean bean = (AddressBean) mBaseProtocal;
                List<AddressItem> addressList = bean.data;
                if (bean.data == null || addressList.size() == 0) {
                    mTvAddress.setHint("请选择地址...");
                }
                for (int i = 0; i < addressList.size(); i++) {
                    if (1 == (addressList.get(i).getDef_addr())) {
                        mTvName.setText("收货人: " + addressList.get(i).getName());
                        mTvPhone.setText(addressList.get(i).getMobile());
                        mTvAddress.setText("收货地址: " + addressList.get(i).getArea() + addressList.get(i).getAddr());
                        refreshFreight();
                        break;
                    }
                }
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(ConfirmOrderActivity.this, msg);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(ConfirmOrderActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    /**
     * 邮费重新计算
     */
    private void refreshFreight() {
        LoadingUtils.createLoadingDialog(context, "正在生成订单...", false);
        BaseHttpLoader http = new BaseHttpLoader(SubmitOrderBean.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.submitOrder(Globals.getToken(), getCartIds());
            }
        };
        http.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                SubmitOrderBean bean = (SubmitOrderBean) mBaseProtocal;
                mDataBean = bean.data;
                initData(true);
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(ConfirmOrderActivity.this, msg);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ConfirmOrderActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    public List<String> getCartIds() {
        ArrayList<String> array = new ArrayList<>();
        for (int i = 0; i < mDataBean.cartList.size(); i++) {
            array.add(mDataBean.cartList.get(i).cart_id);
        }
        return array;
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        LoadingUtils.createLoadingDialog(this, "提交订单中...", false);
        /**
         * @Field("token") String token,
         @Field("shopIds[]") List<String> shopIds,
         @Field("itemIds[]") List<String> itemIds,
         @Field("dlytmplIds[]") List<String> dlytmplIds,
         @Field("postFees[]") List<String> postFees,
         @Field("skuIds[]") List<String> skuIds,
         @Field("cartIds[]") List<String> cartIds,
         @Field("totalPrice") String totalPrice,
         @Field("couponCode") String couponCode
         */
        List<String> shopIds = new ArrayList<>();
        List<String> postFees = new ArrayList<>();
        List<String> dlytmplIds = new ArrayList<>();
        for (int i = 0; i < mDataBean.shopList.size(); i++) {
            shopIds.add(mDataBean.shopList.get(i).shop_id);
            postFees.add(mDataBean.shopList.get(i).postFree);
            dlytmplIds.add(mDataBean.shopList.get(i).template_id);
        }
        List<String> itemIds = new ArrayList<>();
        List<String> skuIds = new ArrayList<>();
        List<String> cartIds = new ArrayList<>();
        for (int i = 0; i < mDataBean.cartList.size(); i++) {
            itemIds.add(mDataBean.cartList.get(i).item_id);
            skuIds.add(mDataBean.cartList.get(i).sku_id);
            cartIds.add(mDataBean.cartList.get(i).cart_id);
        }
        String couponCode = getSelectCouponCode();
        BaseHttpLoader loader = new BaseHttpLoader(ConfirmOrderBean.class, Globals.LISHE_URL) {
            @Override
            public Observable<ResponseBody> structureObservable(NetAPI api) {
                return api.addUserOrder(Globals.getToken(), shopIds,
                        itemIds, dlytmplIds, postFees, skuIds,
                        cartIds, mDataBean.cartTotalPrice, couponCode);
            }
        };
        loader.executor(new ResultListener() {
            @Override
            public void onSuccess(BaseProtocal mBaseProtocal) {
                ConfirmOrderBean bean = (ConfirmOrderBean) mBaseProtocal;
                PayActivity.jump(ConfirmOrderActivity.this,
                        bean.data.paymentId,
                        bean.data.created_time,
                        mDataBean.cartTotalPrice);
                finish();
            }

            @Override
            public void onFail(int errcode, String msg) {
                ToastUtil.showToast(ConfirmOrderActivity.this, msg);
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.showToast(ConfirmOrderActivity.this, R.string.network_or_server_exception);
            }
        });
    }

    public String getSelectCouponCode() {
        String code = "";
        for (int i = 0; i < mDataBean.coupons.size(); i++) {
            if (mDataBean.coupons.get(i).isSelect) {
                code = mDataBean.coupons.get(i).coupon_code;
            }
        }
        return code;
    }

    //-----------------------------选择地址广播处理-----------------------------
    private void regisBrocastReciver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Globals.ACTION_UPADDRESS);
        registerReceiver(receiver, intentFilter);
    }

    BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Globals.ACTION_UPADDRESS)) {
                LoadingUtils.createDefaultDialog(context);
                getReceiveAddress();
            }
        }
    };

}
